using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartLink.Infrastructure
{
    /// <summary>
    /// 动态类型转换帮助类
    /// </summary>
    public static class DynamicToStaticHelper
    {
        /// <summary>
        /// 动态类型转换成简单的类型（属性由简单类型组成）
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="expando">自定义类型实例</param>
        /// <returns>目标类型对象实例</returns>
        public static T ToStatic<T>(object expando)
        {
            var entity = Activator.CreateInstance<T>();

            //ExpandoObject implements dictionary
            var properties = expando as IDictionary<string, object>;

            if (properties == null)
                return entity;

            foreach (var entry in properties)
            {
                var propertyInfo = entity.GetType().GetProperty(entry.Key);
                if (propertyInfo != null)
                    propertyInfo.SetValue(entity, entry.Value, null);
            }
            return entity;
        }
    }
}
